package de.wefunkdroid.core;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import android.os.Environment;
import de.wefunkdroid.core.data.Show;
import de.wefunkdroid.core.data.Track;

public class Parser {

	private static int lastShowNum = 168;
	private static ArrayList<String> links = new ArrayList<String>();
	private static HashMap<String, String> cache = new HashMap<String, String>();

	public Parser() {
	}

	public static void setCache(HashMap<String, String> c) {
		cache = c;
	}

	public static HashMap<String, String> getCache() {
		return cache;
	}

	public static String[] getAllNums() {
		if (links.isEmpty()) {
			links = getAllShowLinks();
			Collections.sort(links);
		}
		String res[] = new String[links.size()];
		for (int i = 0; i < links.size(); i++)
			res[i] = String.valueOf(i + 168);

		return res;
	}

	public static int getLinkSize() {
		return links.size();
	}

	public static ArrayList<String> getShowsall() {
		if (links.isEmpty()) {
			links = getAllShowLinks();
			Collections.sort(links);
		}
		ArrayList<String> res = new ArrayList<String>();
		for (int i = 0; i < links.size(); i++)
			res.add(String.valueOf(i + 168));

		return res;
	}

	private static String getHTMLfromUrl(String url) {
		String str = "";
		try {
			URLConnection con = (new URL(url)).openConnection();
			char buffer[] = new char[8192];
			BufferedInputStream bis = new BufferedInputStream(con
					.getInputStream());
			InputStreamReader isread = new InputStreamReader(bis);
			BufferedReader bread = new BufferedReader(isread);
			for (int read = 0; (read = bread.read(buffer, 0, 8192)) != -1;)
				str = (new StringBuilder(String.valueOf(str))).append(
						new String(buffer, 0, read)).toString();

			bread.close();
			isread.close();
			bis.close();
		} catch (Exception e) {

		}
		return str;
	}

	public static String getDateFromNum(String num) {
		String str = "";
		if (cache.containsKey(num))
			return (String) cache.get(num);
		String url = (new StringBuilder("http://www.wefunkradio.com/show/"))
				.append(num).toString();
		try {
			URLConnection con = (new URL(url)).openConnection();
			con.getInputStream().read();
			String s = con.getURL().toString();
			str = s.substring(s.lastIndexOf("/") + 1, s.length());
			cache.put(num, str);
			System.out.println((new StringBuilder("Added Key=")).append(num)
					.append(" Value=").append(str).append(" to cacheMap")
					.toString());
		} catch (Exception exception) {
		}
		return str;
	}

	private static ArrayList<String> getAllShowLinks() {
		ArrayList<String> res = new ArrayList<String>();
		String t1[] = getHTMLfromUrl("http://www.wefunkradio.com/shows/")
				.split("title=\"Go to WEFUNK Show");
		int lastShow = Integer
				.parseInt(t1[1].substring(1, t1[1].indexOf("\"")));
		lastShowNum = lastShow;
		for (int i = 168; i <= lastShow; i++)
			res.add((new StringBuilder("http://www.wefunkradio.com/show/"))
					.append(i).toString());

		return res;
	}

	public static Show parse(String string, String date) {
		Show show = new Show();
		String t1[] = string.split("var trackextra");
		String t2[] = t1[1].split("var track");
		String infosTmp[] = t2[0].split("\"a\":");
		String timesTmp[] = t2[2].split("mspos");
		if (infosTmp.length > 3) {
			int len = infosTmp.length;
			for (int i = 1; i < len; i++) {
				String si = infosTmp[i];
				String st = timesTmp[i + 1];
				if (si.indexOf("\"") > -1 && si.indexOf(",") > -1
						&& si.indexOf("\"}") > -1 && st.indexOf(":") > -1
						&& st.indexOf(",") > -1) {
					Track t = new Track(si.substring(1, si.indexOf(":") - 5),
							si
									.substring(si.indexOf(",") + 6, si
											.indexOf("\"}")), st.substring(st
									.indexOf(":") + 1, st.indexOf(",")));
					System.out.println((new StringBuilder()).append(t).append(
							" ").append(t.getMsPos()).toString());
					show.addTrack(t);
				}
			}

		} else {
			show.addTrack(new Track("ALL", "NoPlayList", "0"));
		}
		String k1[] = string.split("<div id=\"hwrap\">");
		show.setNum(k1[1].substring(4, k1[1].indexOf("</h1>")).replaceAll(
				"Show ", ""));
		show.setDate(date);
		return show;
	}

	public static String getALink(Show s) {
		String sdPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		if (!sdPath.endsWith("/"))
			sdPath = (new StringBuilder(String.valueOf(sdPath))).append("/")
					.toString();
		sdPath = (new StringBuilder(String.valueOf(sdPath)))
				.append(".wedroid/").toString();
		File f = new File((new StringBuilder(String.valueOf(sdPath))).append(
				"WeFunk_Show_").append(s.getNum()).append("_").append(
				s.getDate()).append(".mp3").toString());
		System.out.println((new StringBuilder("testing for ")).append(
				f.toString()).toString());
		if (f.exists()) {
			System.out.println("playing from cache ;)");
			return f.toString();
		} else {
			return (new StringBuilder(
					"http://www.wefunkradio.com/mirror/stream/")).append(
					s.getDate()).append("/").append(s.getNum()).toString();
		}
	}

	public static int getLastShowNum() {
		return lastShowNum;
	}

}
